/**
 * 
 */
package com.frogs.ucenter.service;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.frogs.framework.component.cache.Cache;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;

/**
 * Service抽象基类
 * 
 * @author wushubin
 */
public abstract class AbsService {
	
	/** api请求超时时间设置 */
	protected static final int TIME_OUT = 50000;

	/** api基础url地址缓存 */
	private Map<String, ApiUrl> apiBaseUrlCache = Collections.synchronizedMap(new HashMap<String, ApiUrl>());
	
	private Logger log = LoggerFactory.getLogger(AbsService.class);

	@Resource
	protected Map<String, String> ucenterApiConfig;
	
	@Resource
	protected Map<String, String> mallApiConfig;
	
	@Resource
	protected Map<String, String> traceApiConfig;
	
	@Resource
	protected Map<String, String> payApiConfig;
	
	@Resource
	protected Map<String, String> promotionApiConfig;
	
	@Resource(name="xmemcached")
	public Cache cache;

	/**
	 * 获取包含uuid、token参数的基础url地址，如：<br>
	 * @param apiUrlKey 指定api地址的KEY值
	 * @return
	 */
	protected ApiUrl buildUcenterApiBaseUrl(String apiUrlKey) {
		
		if (apiBaseUrlCache.containsKey(apiUrlKey)) {// 先从缓存查
			return apiBaseUrlCache.get(apiUrlKey);
		}		        
		
		String[] keyvals = {ApiUrlParamEnum.appId.getParamName() , ucenterApiConfig.get("APP_ID")};
		
		String apiUrl = ucenterApiConfig.get(apiUrlKey);
		ApiUrl url = new ApiUrl(apiUrl, keyvals);
		
		apiBaseUrlCache.put(apiUrlKey, url);
		return url;
	}
	
	protected ApiUrl buildMallApiBaseUrl(String apiUrlKey) {
		
		if (apiBaseUrlCache.containsKey(apiUrlKey)) {// 先从缓存查
			return apiBaseUrlCache.get(apiUrlKey);
		}		        
		
		String[] keyvals = {"uuid" , mallApiConfig.get("UUID") ,"token",mallApiConfig.get("ACCESS_TOKEN")};
		
		String apiUrl = mallApiConfig.get(apiUrlKey);
		ApiUrl url = new ApiUrl(apiUrl, keyvals);
		
		apiBaseUrlCache.put(apiUrlKey, url);
		return url;
	}
	
	protected ApiUrl buildTraceApiBaseUrl(String apiUrlKey) {
		
		if (apiBaseUrlCache.containsKey(apiUrlKey)) {// 先从缓存查
			return apiBaseUrlCache.get(apiUrlKey);
		}		        
		
		String[] keyvals = {"uuid" , traceApiConfig.get("UUID") ,"token",traceApiConfig.get("ACCESS_TOKEN")};
		
		String apiUrl = traceApiConfig.get(apiUrlKey);
		ApiUrl url = new ApiUrl(apiUrl, keyvals);
		
		apiBaseUrlCache.put(apiUrlKey, url);
		return url;
	}
	
	protected ApiUrl buildPayApiBaseUrl(String apiUrlKey) {
		
		if (apiBaseUrlCache.containsKey(apiUrlKey)) {// 先从缓存查
			return apiBaseUrlCache.get(apiUrlKey);
		}		        
		
		String[] keyvals = {"uuid" , payApiConfig.get("UUID") ,"token",payApiConfig.get("ACCESS_TOKEN")};
		
		String apiUrl = payApiConfig.get(apiUrlKey);
		ApiUrl url = new ApiUrl(apiUrl, keyvals);
		
		apiBaseUrlCache.put(apiUrlKey, url);
		return url;
	}
	
	protected ApiUrl buildPromotionApiBaseUrl(String apiUrlKey) {
		
		if (apiBaseUrlCache.containsKey(apiUrlKey)) {// 先从缓存查
			return apiBaseUrlCache.get(apiUrlKey);
		}		        
		String[] keyvals = {ApiUrlParamEnum.appId.getParamName() , promotionApiConfig.get("APP_ID")};

		String apiUrl = promotionApiConfig.get(apiUrlKey);
		ApiUrl url = new ApiUrl(apiUrl, keyvals);
		
		apiBaseUrlCache.put(apiUrlKey, url);
		return url;
	}
		

	/**
	 * 向指定api接口发起请求
	 * 
	 * @param apiUrlKey 请求连接（不带参数）
	 * @param method 提交方式get/post
	 * @param keyvals 请求参数
	 */
	protected Object requestApi(String apiUrlKey,Method method,String[] keyvals) throws Exception {
		log.info(apiUrlKey + "," + Arrays.deepToString(keyvals));
		Connection.Response res = Jsoup.connect(apiUrlKey)
				.header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0;)")
				.header("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*")
			    .method(method)
			    .ignoreContentType(true)
			    .data(keyvals).timeout(TIME_OUT)
			    .execute();
		return JSON.parse(res.body());
    }
	
}
